package com.bkybk.boota.thymeleaf.controller;

import com.bkybk.boota.thymeleaf.domain.User;
import com.bkybk.boota.thymeleaf.repository.UserRepository;
import com.sun.org.apache.xpath.internal.operations.Mod;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

@RestController
@RequestMapping(value = "users")
public class UserController {

    @Autowired
    private UserRepository userRepository;

    @GetMapping(value = "/index")
    public ModelAndView list(Model model){
        model.addAttribute("userList", userRepository.findAll());
        model.addAttribute("title", "用户管理");
        return new ModelAndView("users/list", "userModel", model);
    }

    @GetMapping(value = "/get/{id}")
    public ModelAndView view(@PathVariable("id")Long id, Model model){
        model.addAttribute("user", userRepository.findOne(id));
        model.addAttribute("title", "用户信息查看");
        return new ModelAndView("users/view", "userModel", model);
    }

    @GetMapping(value = "/form")
    public ModelAndView form(Model model){
        model.addAttribute("user", new User(null, null, null));
        model.addAttribute("title", "创建用户");
        return new ModelAndView("users/form", "userModel", model);
    }

    @PostMapping(value = "/summit")
    public ModelAndView saveOrUpdate(User user){
        userRepository.save(user);
        return new ModelAndView("redirect:/users/index");
    }

    @GetMapping(value = "/delete/{id}")
    public ModelAndView delete(@PathVariable("id")Long id){
        userRepository.delete(id);
        return new ModelAndView("redirect:/users/index");
    }

    @GetMapping(value = "/modify/{id}")
    public ModelAndView modify(@PathVariable("id") Long id, Model model){
        User user = userRepository.findOne(id);
        model.addAttribute("user", user);
        model.addAttribute("title", "修改用户");
        return new ModelAndView("users/form", "userModel", model);
    }


}
